<template>
  <div>
    <el-dialog
      :title="titleInfo"
      v-model="dialogTableVisible"
      :close-on-click-modal="false"
      @close="closeDialogFormVisible"
    >
      <div class="content-info">
        <el-form
          ref="queryInfoRef"
          :rules="listQueryRules"
          :model="queryInfo"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="评估报告图" prop="imageUrl">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :limit="1"
              :action="''"
              accept=".png,.jpg,.jpeg"
              :on-progress="handlePictureCardPreview"
              :data="additionalData"
              :http-request="UploadFileFn"
              :before-upload="handleBeforeUpload"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                prop="imageUrl"
              />
            </el-upload>
          </el-form-item>
          <el-form-item label="公司名称" prop="company_id">
            <el-select
              class="!w-[300px]"
              v-model="queryInfo.company_id"
              clearable
              placeholder="请选择公司名称"
            >
              <el-option
                v-for="item in companyIdList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="抵押物" prop="name">
            <el-input
              placeholder="请输入抵押物"
              clearable
              v-model="queryInfo.name"
              auto-complete="off"
              class="!w-[300px]"
            />
          </el-form-item>
          <el-form-item label="评估价值" prop="appraisal">
            <el-input
              v-model="queryInfo.appraisal"
              placeholder="请输入评估价值"
              clearable
              @input="
                queryInfo.appraisal = queryInfo.appraisal.replace(/\D/g, '')
              "
              auto-complete="off"
              maxlength="10"
              class="!w-[300px]"
            />
          </el-form-item>
          <el-form-item label="登记情况" prop="register">
            <el-input
              placeholder="请输入抵押物"
              clearable
              v-model="queryInfo.register"
              auto-complete="off"
              class="!w-[300px]"
            />
          </el-form-item>
          <el-form-item label="登记时间">
            <el-date-picker
              v-model="queryInfo.register_time"
              type="date"
              placeholder="选择登记时间"
              value-format="YYYY-MM-DD"
              class="!w-[300px]"
            />
          </el-form-item>
          <el-form-item label="备注" prop="notes">
            <el-input
              placeholder="请输入备注"
              clearable
              v-model="queryInfo.notes"
              auto-complete="off"
              class="!w-[300px]"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="closeDialogFormVisible" type="danger"
              >取消</el-button
            >
            <el-button type="primary" :loading="loading" @click="handleSubmit">
              提交
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getSessionKey } from "@/utils/auth";
import { getuFile } from "@/api/user";
import OSS from "ali-oss";
import {
  reactive,
  ref,
  inject,
  onMounted,
  defineProps,
  defineEmits,
  nextTick,
  defineExpose,
  watch
} from "vue";
const chekcPhone = (rule, value, callback) => {
  const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (!value) {
    return callback(new Error("手机号码不能为空"));
  } else if (!reg.test(value)) {
    return callback(new Error("手机号格式不正确"));
  } else {
    callback();
  }
};
const registerList = ref([
  {
    label: "已登记",
    value: 1
  },
  {
    label: "未登记",
    value: 2
  }
]);
import { companySelect } from "@/api/loanMortgageList";
const companyIdList = ref([]);
const listQueryRules = {
  company_id: [{ required: true, message: "请选择公司ID", trigger: "blur" }],
  // appraisal: [{ required: true, message: "请输入评估价值", trigger: "blur" }],
  name: [{ required: true, message: "请输入抵押物", trigger: "blur" }]
};
const imageUrl = ref(
  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);
const queryInfoRef = ref("");
const additionalData = reactive({
  // 这里添加你需要传递的额外参数
  type: "admin",
  action: "loan"
});
const props = defineProps({
  titleInfo: {
    type: String,
    default: ""
  },
  isEdit: {
    type: String,
    default: ""
  }
});
const dialogTableVisible = ref(false);
const queryInfo = ref({
  company_id: "",
  name: "",
  appraisal: "",
  register: "",
  register_time: "",
  image: "",
  notes: ""
});
const opneDialogVisible = rowData => {
  if (props.isEdit == 1) {
    queryInfo.value = { ...rowData };
    queryInfo.value.register = Number(rowData.register);
  }
  const parmas = {
    name: "",
    admin_id: getSessionKey().admin_id
  };
  companySelect(parmas).then(res => {
    if (res.code == 200) {
      console.log(res.data);

      companyIdList.value = res.data;
    }
  });
  dialogTableVisible.value = true;
};
// 取消
const closeDialogFormVisible = () => {
  dialogTableVisible.value = false;
  imageUrl.value = `https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`;
  queryInfo.value = {
    status: 1
  };
};
const emit = defineEmits(["handleSubmit"]);
// 提交
const handleSubmit = () => {
  queryInfoRef.value.validate(valid => {
    if (valid) {
      // 添加
      const parmas = { ...queryInfo.value };
      emit("handleSubmit", parmas);
    }
  });
};
// 上传图片
const handleBeforeUpload = file => {
  const filesInfo = file.size / 1024 / 1024 < 2;
  if (!filesInfo) {
    ElMessageBox.alert("上传头像图片大小不能超过 2MB!");
  }
  // return new Promise((resolve, reject) => {
  //   const reader = new FileReader();
  //   reader.onload = e => {
  //     // 转换成功，得到Base64字符串
  //     const base64 = e.target.result;
  //     // 处理Base64字符串，例如可以在这里发起接口请求
  //     const params = {
  //       ...additionalData,
  //       file: base64
  //     };
  //     getuFile(params).then(res => {
  //       if (res.code == 200) {
  //         imageUrl.value = base64;
  //         queryInfo.value.image = res.data;
  //       }
  //     });
  //   };
  //   reader.onerror = reject;
  //   reader.readAsDataURL(file); // 转换文件为Base64
  // });
};

// 上传图片
const client = new OSS({
  // uploadImageUrl: ` http://yuandacaiwuoss.52dashi.com`, // 默认存在根目录，可根据需求改
  region: "oss-cn-wuhan-lr", // bucket所在的区域， 默认oss-cn-hangzhou
  //secure: true, // secure: 配合region使用，如果指定了secure为true，则使用HTTPS访问
  accessKeyId: "LTAI5tQ54726RmEkCVn9yYeJ", // 通过阿里云控制台创建的AccessKey
  accessKeySecret: "ZgiT3HgIngnwXRylGZuXeZPTOMkATD", // 通过阿里云控制台创建的AccessSecret
  bucket: "yuandacaiwu" // 通过控制台或PutBucket创建的bucket
});
const UploadFileFn = file => {
  const fileName = ref(`/loan/collateral/${Date.parse(new Date())}`);
  console.log(file, "sahngchuan");
  client.put(fileName.value, file.file).then(res => {
    // console.log(res);
    queryInfo.value.image = fileName.value;
    imageUrl.value = res.url;
    // console.log(listQuery.image);
  });
};

defineExpose({ opneDialogVisible, closeDialogFormVisible }); //子组件需要把数据导出去
</script>

<style lang="scss" scoped>
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
